<template>
	<div class="uploadbottom">
		<div class="uploadleft">
			<el-input placeholder="请输入分组名称" v-model="input1" class="searchinput1">
				<i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;"></i>
			</el-input>
			<el-button class="showallbtn" size="medium" @click="showAllFiles">全部文件</el-button>
			<el-tree :data="data" @node-click="handleNodeClick" class="uploadtree" highlight-current
				:filter-node-method="filterNode" ref="tree"></el-tree>
		</div>
		<div class="uploadright">
			<div class="uploadmaintop">
				<el-button size="small" type="primary" onclick="document.getElementById('upload4').click()">上传文件</el-button>
				<input type="file" name="upload4" id="upload4" style="display: none;" multiple="multiple"
					@change="selFile($event)" />
				<i :class="liststyle?'el-icon-s-order uploadqiehuan':'el-icon-s-grid uploadqiehuan'"
					@click="clickListStyle"></i>
				<el-select v-model="value" placeholder="选择排序" class="el-menus" @change="handleSelect">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
				<el-input placeholder="查找图片名称" v-model="input2" class="searchinput2">
					<i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;"
						@click="searchFilesName"></i>
				</el-input>
			</div>
			<div class="uploadmainfile">
				<transition name="el-fade-in-linear">
					<el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
						@selection-change="handleSelectionChange" height="460" v-if="liststyle">
						<el-table-column type="selection" width="30">
						</el-table-column>
						<el-table-column label="图片" width="300">
							<template slot-scope="scope">
								<div @click="playFiles((scope.row.path+scope.row.name),scope.row.name)">
									<el-image style="width: 50px;height: 30px;display:inline-block" :src="scope.row.src" fit="contain"></el-image>
									<div style="display: inline-block;padding-left: 10px;">
										<p>{{scope.row.name}}</p>
										<p>{{scope.row.time}}</p>
									</div>
									<el-progress v-if="progressFlag&&(scope.$index<count?true:false)"
										:percentage="loadProgress[scope.$index]">
									</el-progress>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="大小" width="120">
							<template slot-scope="scope">
								<span>{{scope.row.size}}M</span>
							</template>
						</el-table-column>
						<el-table-column prop="createtime" label="上传时间" show-overflow-tooltip align="right">
						</el-table-column>
					</el-table>
				</transition>
				<transition name="el-fade-in">
					<el-row v-show="!liststyle" class="cardfile" :gutter="10">
						<el-checkbox-group @change="handleCheckedCardsChange" v-model="multipleSelection">
							<el-col :span="6" v-for="(item, index) in tableData" :key="index" 
								style="margin-bottom: 20px;">
								<el-card :body-style="{ padding: '0px' }">
									<img :src="item.src" class="image" height="120px" @click="playFiles((item.path+item.name),item.name)">
									<div style="padding: 14px;">
										<el-checkbox :label="item" class="elcheckbox">{{item.name|formatStr}}
										</el-checkbox><span style="margin-left: 5px;">{{item.name|formatStr}}</span>
										<div class="bottom clearfix">
											<time class="time">{{item.time}} {{item.resolution}}</time>
											<el-button type="text" class="button">{{item.size}}M</el-button>
										</div>
									</div>
								</el-card>
								<el-progress v-if="progressFlag&&(index<count?true:false)"
									:percentage="loadProgress[index]">
								</el-progress>
							</el-col>
						</el-checkbox-group>
					</el-row>
				</transition>
			</div>
			<div class="uploadmainbottom">
				<el-checkbox @change="allChoose" class="elcheckbox" v-model="checkAll" v-if="liststyle">当页全选
				</el-checkbox>
				<el-checkbox v-model="checkAll" @change="handleCheckAllChange" class="elcheckbox" v-if="!liststyle">当页全选
				</el-checkbox>
				<el-link type="danger" class="deletefiles" @click="deleteFiles">删除</el-link>
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total" class="elpagination">
				</el-pagination>
			</div>
		</div>
		<el-dialog title="文件" style="text-align: center;" :visible.sync="filesplayshow" width="30%" :before-close="handleClose" append-to-body>
			<el-button @click="downloadFile" type="primary">下载文件-{{downloadfilename}}</el-button>
		</el-dialog>
	</div>
</template>

<script>
	import uploadfileMixin from '@/mixin/uploadossfile.js';
	import deletefileMixin from '@/mixin/deleteossfile.js';
	import showfileMixin from '@/mixin/showossfile.js';
	import {
		fenZuData,
		insertUploadFiles,
		showUploadFiles,
		deleteUploadFiles,
		houtairesbucket
	}
	from '../../api/index';
	export default {
		filters: {
			formatStr(str) {
				if (str.length > 10) {
					return str.toString().substr(0, 10) + '...';
				} else {
					return str;
				}
			}
		},
		mixins: [uploadfileMixin, deletefileMixin, showfileMixin],
		data() {
			return {
				input1: "",
				input2: "",
				data: [],
				liststyle: 1,
				options: [{
					value: '选项1',
					label: '按文件名（a-z）'
				}, {
					value: '选项2',
					label: '按文件名（z-a）'
				}, {
					value: '选项3',
					label: '文件大小（大-小）'
				}, {
					value: '选项4',
					label: '文件大小（小-大）'
				}, {
					value: '选项5',
					label: '上传时间（新-旧）'
				}, {
					value: '选项6',
					label: '上传时间（旧-新）'
				}],
				value: '',
				tableData: [{
					name: '图片1',
					time: '00:00:34',
					size: '1.7',
					date: '2016-05-03 00:00:00',
					src: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
					resolution: '400*400'
				}],
				checkAll: false,
				multipleSelection: [],
				count: 0,
				progressFlag: false,
				loadProgress: [],
				nodedata: "",
				page: 1,
				limit: 10,
				total: 0,
				node: 'all',
				sortid: '',
				order: '',
				filesplayshow:false,
				player:'',
				downloadfileurl:'',
				downloadfilename:''
			}
		},
		methods: {
			handleNodeClick(data) { //点击左边分组然后对应显示图片列表
				this.nodedata = data;
				this.page = 1;
				if (data.pid == 0) {
					this.node = 'root';
				} else {
					this.node = 'children';
				}
				this.input2 = "";
				this.sortid = data.id
				this.getFilesData();
			},
			handleSelect() { //选择排序对应显示排序列表
				this.page = 1;
				this.order = this.value;
				this.getFilesData();
			},
			handleSelectionChange(val) { //全选表格
				this.multipleSelection = val;
				if (val.length == this.tableData.length) {
					this.checkAll = true;
				} else if (val.length == 0) {
					this.checkAll = false;
				}
			},
			allChoose(val) { //全轩列表当前页
				if (val) {
					for (let i in this.tableData) {
						this.$nextTick(() => {
							this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true);
						});
					}
					this.multipleSelection=this.tableData;
				} else {
					this.$refs.multipleTable.clearSelection();
					this.multipleSelection=[];
				}
			},
			handleSizeChange(val) { //选择每页显示多少条
				this.limit = val;
				this.getFilesData();
				//console.log(`每页 ${val} 条`);
			},
			handleCurrentChange(val) { //显示当前页列表
				this.page = val;
				this.getFilesData();
				//console.log(`当前页: ${val}`);
			},
			handleCheckedCardsChange(value) { //如果卡片一个一个全部选中了，就勾选全部选中复选框
				this.multipleSelection=value;
				let checkedCount = value.length;
				this.checkAll = checkedCount === this.tableData.length;
				console.log(this.multipleSelection);
			},
			clickListStyle() { //切换显示样式列表或卡片
				if (this.liststyle) { //列表模式转卡片模式
					this.liststyle = false;
				} else {
					this.liststyle = true; //卡片模式转列表模式
					for (let i of this.multipleSelection) {
						this.$nextTick(() => {
							this.$refs.multipleTable.toggleRowSelection(i, true);
						});
					}
				}
			},
			handleCheckAllChange(val) { //全选卡片当前页面复选框
				this.multipleSelection = val ? this.tableData : [];
			},
			getSortDir() { //得到分组目录
				fenZuData({
					typeid:4
				}).then((res) => {
					var classifyList = res.data.list;
					for (let i = 0; i < classifyList.length; i++) {
						this.data.push({
							pid: '',
							id: '',
							label: '',
							children: []
						});
						this.data[i].pid = classifyList[i].pid;
						this.data[i].id = classifyList[i].id;
						this.data[i].label = classifyList[i].title;
						if (classifyList[i]._child) {
							for (let j = 0; j < classifyList[i]._child.length; j++) {
								this.data[i].children.push({
									pid: classifyList[i]._child[j].pid,
									id: classifyList[i]._child[j].id,
									label: classifyList[i]._child[j].title,
									plabel: classifyList[i].title
								});
							}
						}
					}
					//console.log(this.data);
				});

			},
			async getFilesData() { //按一定条件得到上传图片列表
				var res = await showUploadFiles({
					node: this.node,
					sortid: this.sortid,
					page: this.page,
					limit: this.limit,
					search: this.input2,
					order: this.order
				});
				this.tableData = res.data.filesdata;
				this.total = res.data.total;
				//this.$parent.total = this.total;
				this.$emit('updateFilesTotal',this.total);
			},
			filterNode(value, data) { //分组过滤input
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			async selFile(e) { //选择上传文件
				if (!this.nodedata) {
					this.$message.error('请创建分组后选择分组再上传！');
					document.getElementById('upload4').value = "";
					return;
				}
				let files = e.target.files;
			   for (let k = 0; k < files.length; k++) {
					const tmpfiles = files[k].name.split('.');
					const extfilesname = tmpfiles.pop();
					const extfilesList = ['txt','jpg','png','pdf','doc','xls','ppt','docx','xlsx','pptx','rar','zip'];
					const isfilesValid = extfilesList.includes(extfilesname);
					if (!isfilesValid) {
					var	result = true;
						break;
					}else{
					var	result=false;
					}
				}
				if(result){
					this.$message.error(`仅支持txt、jpg、png、pdf、doc、xls、ppt、docx、xlsx、pptx、rar、zip格式的文件`);
					return;
				}
				this.count = files.length;
				let filearr = [];
				for (let i = 0; i < files.length; i++) {
					const tmpfiles = files[i].name.split('.');
					const extfilesname = tmpfiles.pop();
					switch(extfilesname){
						case 'txt':
                         var imgsrc='/image/txt.jpg';    
						break;
						case 'jpg':
						case 'png':
                         var imgsrc=getObjectURL(files[i]);
						break;
						case 'pdf':
						 var imgsrc='/image/pdf.jpg'; 
						break;
						case 'doc':
						case 'docx':
						 var imgsrc='/image/doc.jpg'; 
						break;
						case 'xls':
						case 'xlsx':
						 var imgsrc='/image/xls.jpg'; 
						break;
						case 'ppt':
						case 'pptx':
						 var imgsrc='/image/ppt.jpg'; 
						break;
						case 'rar':
						case 'zip':
						 var imgsrc='/image/rar.jpg';
						break;
					}
					//const imgsrc = '/image/files.jpg';
					filearr[i] = {
						name: files[i].name,
						size: (files[i].size / 1024 / 1024).toFixed(2),
						createtime: await jsDateFormatter(new Date()),
						src: imgsrc
					};
					this.tableData.splice(0, 0, filearr[i]);
				}
				this.progressFlag = true;
				let username = localStorage.getItem('ms_username');
				let shopuuid = localStorage.getItem('shopuuid');
				if(this.node=="root"){
					let parentdir = this.nodedata.label;
					var path = 'files/' + username + '/' + shopuuid + '/' + parentdir+'/';
				}else if(this.node=="children"){
					let parentdir = this.nodedata.plabel;
					let currentdir = this.nodedata.label;
					var path = 'files/' + username + '/' + shopuuid + '/' + parentdir + '/' + currentdir + '/';
				}
				//console.log(parentdir);
				for (let j = 0; j < files.length; j++) {
					let bucket=houtairesbucket;
					let url = await this.fileUpload(files[j], path + files[j].name, j, this, bucket, 4); //上传到oss，2代表上传文件
					filearr[j].src = url;
					filearr[j].path = path;
					if(files[j].size<50*1024*1024){
					let res = await insertUploadFiles({
						file: JSON.stringify(filearr[j]),
						path,
						bucket,
						sortpid: this.nodedata.pid,
						sortid: this.nodedata.id,
					}); //插入数据库
					//console.log(res);
					if (res.code == -1) {
						let filepath = path + files[j].name;
						this.deleteMultiFile([filepath]);
						this.$message.error('保存数据库出错了！');
					} else if (res.code == -2) {
						this.$message.error('请不要上传相同的文件');
					}
					}else{
						this.$message.error('请上传小于50M的文件')
					}
				}
				this.getFilesData();
				this.multipleSelection=[];
				this.checkAll=false;
			},
			async deleteFiles() { //删除图片
				//console.log(this.multipleSelection);
				if (this.multipleSelection.length == 0) {
					this.$message.error("请选择文件后再来删除");
					return;
				}
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					let pathname = [];
					let ids = [];
					for (let i = 0; i < this.multipleSelection.length; i++) {
						pathname.push(this.multipleSelection[i].path + this.multipleSelection[i].name);
						ids.push(this.multipleSelection[i].id);
					}
					ids=ids.toString();
					let deleteres = await deleteUploadFiles({
						ids
					});
					//console.log(deleteres);
					if (deleteres.code == 1) {
						const newItems = [...this.multipleSelection];
						for (let j = 0; j < newItems.length; j++) {
						let index = this.tableData.indexOf(newItems[j]);
						if (index > -1) {
							this.tableData.splice(index, 1);
						}
					    }
						this.multipleSelection=[];
						this.deleteMultiFile(pathname, houtairesbucket);
						this.getFilesData();
					} else {
						this.$message.error('删除失败！');
					}
				});
			},
			showAllFiles() { //显示所有图片
				this.node = 'all';
				this.page = 1;
				this.input2 = "";
				this.getFilesData();
			},
			searchFilesName() { //搜索指定的图片
				this.page = 1;
				this.getFilesData();
			},
			async playFiles(path,filename) {
				//let path="files/admin/25/平面设计/室内设计/6781f56fd516a2be3ccf78de88d6ea81.mp3";
				this.filesplayshow = true;
				this.downloadfileurl = await this.getSignatureUrl(path); //bucket默认xuejingres,暂时可以不填写
				this.downloadfilename=filename;
				//console.log(filename)
			},
			downloadFile(){
				Download(this.downloadfileurl,this.downloadfilename); 
			},
			handleClose(){
				this.filesplayshow=false;
			}
			// ,test() {
			// 	alert(1);
			// }
		},
		created() {
			this.getSortDir(); //得到分组
			this.showAllFiles(); //得到所有图片列表
		},
		watch: {
			input1(val) {
				this.$refs.tree.filter(val);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uploadbottom {
		width: 98%;
		height: 550px;
		display: flex;
		margin-left: 10px;

		.uploadleft {
			border: 1px solid #ccc;
			width: 25%;
			height: 550px;
			text-align: center;

			.showallbtn {
				margin-top: 10px;
				width: 100%;
				border-left: none;
				border-right: none;
			}

			.searchinput1 {
				width: 90%;
				margin-top: 10px;
				display: inline-block;
			}

			.uploadtree {
				//padding-left: 10px;
				margin-top: 10px;

			}
		}

		.uploadright {
			margin-left: 15px;
			width: 75%;
			height: 550px;

			.uploadmaintop {
				height: 45px;
				width: 100%;
				line-height: 45px;
				position: relative;

				.el-menus {
					width: 160px;
					display: inline-block;
					margin-left: 3%;
				}

				.uploadqiehuan {
					line-height: 45px;
					margin-left: 25%;
					font-size: 22px;
					display: inline-block;
				}

				.searchinput2 {
					position: absolute;
					right: 0;
					width: 30%;
					margin-left: 1%;
					display: inline-block;
				}
			}

			.uploadmainfile {
				margin-top: 10px;

				.cardfile {
					height: 460px;
					overflow-y: scroll;

					.time {
						font-size: 13px;
						color: #999;
					}

					.bottom {
						margin-top: 13px;
						line-height: 12px;
					}

					.button {
						padding: 0;
						float: right;
					}

					.image {
						width: 100%;
						display: block;
					}

					.clearfix:before,
					.clearfix:after {
						display: table;
						content: "";
					}

					.clearfix:after {
						clear: both
					}
				}
			}

			.uploadmainbottom {
				margin-top: 10px;
				position: relative;
				height: 40px;

				.elcheckbox {
					position: absolute;
					left: 10px;
					top: 5px;
				}

				.deletefiles {
					position: absolute;
					left: 100px;
					top: 5px;
				}

				.elpagination {
					position: absolute;
					right: 0;
				}
			}
		}
	}
</style>
